const user = require("../models/user");
const jwt = require('jsonwebtoken');
const bcrypt = require('bcryptjs');

const login = async function (ctx) {
    const data = {
        userName: ctx.request.body.userName,
        password: ctx.request.body.password
    }

    const userInfo = await user.login(data);
    if (userInfo != null) { //查询无此用户会返回null
        if (!bcrypts.compareSync(ctx.request.body.password, userInfo.password)) {
            ctx.body = {
                success: false,
                msg: '密码错误！'
            }
        } else { //用户名密码正确
            const userToken = {
                name: userInfo.userName,
                id: userInfo.id
            }
            const secret = 'vue-token-json' //指定秘钥，用来判断token的合法性，
            const token = jwt.sign(userToken, secret);

            ctx.body = {
                success: true,
                token: token
            }
        }
    } else {
        ctx.body = {
            success: false,
            msg: '用户不存在'
        }
    }
}

const regesiter = async function (ctx) {
    var salt = bcrypt.genSaltSync(10);
    var hash = bcrypt.hashSync(ctx.request.body.password, salt);
    const data = {
        userName: ctx.request.body.userName,
        password: hash
    }
    const result = await user.regesiter(data);
    ctx.body = {
        success: true
    }
}

module.exports = { 
    login,
    regesiter
}